Matching Market

This simple model consists of a buyer, a supplier, and a market.

The buyer represents a group of customers whose willingness to pay for a single unit of the good is captured by a vector of prices wta. You can initiate the buyer with a set_quantity function which randomly assigns the willingness to pay according to your specifications. You may ask for these willingness to pay quantities with a getbid function.

The supplier is similiar, but instead the supplier is willing to be paid to sell a unit of technology. The supplier for instance may have non-zero variable costs that make them unwilling to produce the good unless they receive a specified price. Similarly the supplier has a get_ask function which returns a list of desired prices.

The willingness to pay or sell are set randomly using uniform random distributions. The resultant lists of bids are effectively a demand curve. Likewise the list of asks is effectively a supply curve. A more complex determination of bids and asks is possible, for instance using time of year to vary the quantities being demanded.

New in version 2

The actioneer now has a book in the form of a Pandas Dataframe to keep track of the bids and aks being submitted to the market.

Microeconomic Foundations

The market assumes the presence of an auctioneer which will create a book, which seeks to match the bids and the asks as much as possible. If the auctioneer is neutral, then it is incentive compatible for the buyer and the supplier to truthfully announce their bids and asks. The auctioneer will find a single price which clears as much of the market as possible. Clearing the market means that as many willing swaps happens as possible. You may ask the market object at what price the market clears with the get_clearing_price function. You may also ask the market how many units were exchanged with the get_units_cleared function.

Agent-Based Objects

The following section presents three objects which can be used to make an agent-based model of an efficient, two-sided market.


In [14]:
%matplotlib inline
import random as rnd
import pandas as pd

class Seller():
    wta = []
    def __init__(self,name):
        self.name = name
    
    # the supplier has n quantities that they can sell
    # they may be willing to sell this quantity anywhere from a lower price of l
    # to a higher price of u
    def set_quantity(self,n,l,u):
        wta = []
        for i in range(n):
            p = rnd.uniform(l,u)
            self.wta.append(p)

    def get_name(self):
        return self.name
    
    def get_asks(self):
        return self.wta

class Buyer():
    
    def __init__(self, name):
        self.wtp = []
        self.name = name
        
    # the supplier has n quantities that they can buy
    # they may be willing to sell this quantity anywhere from a lower price of l
    # to a higher price of u
    def set_quantity(self,n,l,u):
        for i in range(n):
            p = rnd.uniform(l,u)
            self.wtp.append(p)
     
    def get_name(self):
        return self.name
    
    # return list of willingness to pay
    def get_bids(self):
        return self.wtp

class Book():
    ledger = pd.DataFrame(columns = ("role","name","price","cleared"))

    
    def set_asks(self,seller_list):
        # ask each seller their name
        # ask each seller their willingness
        # for each willingness append the data frame
        for seller in seller_list:
            seller_name = seller.get_name()
            seller_price = seller.get_asks()
            for price in seller_price:
                self.ledger=self.ledger.append({"role":"seller","name":seller_name,"price":price,"cleared":"in process"},
                                               ignore_index=True)

    def set_bids(self,buyer_list):
        # ask each seller their name
        # ask each seller their willingness
        # for each willingness append the data frame
        for buyer in buyer_list:
            buyer_name = buyer.get_name()
            buyer_price = buyer.get_bids()
            for price in buyer_price:
                self.ledger=self.ledger.append({"role":"buyer","name":buyer_name,"price":price,"cleared":"in process"},
                                               ignore_index=True)

    def update_ledger(self,ledger):
        self.ledger = ledger
        
    def get_ledger(self):
        return self.ledger
    
        
class Market():
    count = 0
    last_price = ''
    book = Book()
    b = []
    s = []
    ledger = ''
    
    #def __init__(self):

    def add_buyer(self,buyer):
        self.b.append(buyer)
        
    def add_seller(self,seller):
        self.s.append(seller)
    
    def set_book(self):
        self.book.set_bids(self.b)
        self.book.set_asks(self.s)
    
    def get_ledger(self):
        self.ledger = self.book.get_ledger()
        return self.ledger
    
    def get_bids(self):
        # this is a data frame
        ledger = self.book.get_ledger()
        rows= ledger.loc[ledger['role'] == 'buyer']
        # this is a series
        prices=rows['price']
        # this is a list
        bids = prices.tolist()
        return bids
    
    def get_asks(self):
        # this is a data frame
        ledger = self.book.get_ledger()
        rows = ledger.loc[ledger['role'] == 'seller']
        # this is a series
        prices=rows['price']
        # this is a list
        asks = prices.tolist()
        return asks
    
    # return the price at which the market clears
    # this fails because there are more buyers then sellers
    
    def get_clearing_price(self):
        # buyer makes a bid starting with the buyer which wants it most
        b = self.get_bids()
        s = self.get_asks()
        # highest to lowest
        self.b=sorted(b, reverse=True)
        # lowest to highest
        self.s=sorted(s, reverse=False)
        
        # find out whether there are more buyers or sellers
        # then drop the excess buyers or sellers; they won't compete
        n = len(b)
        m = len(s)
        
        # there are more sellers than buyers
        # drop off the highest priced sellers 
        if (m > n):
            s = s[0:n]
            matcher = n
        # There are more buyers than sellers
        # drop off the lowest bidding buyers 
        else:
            b = b[0:m]
            matcher = m
        
        # It's possible that not all items sold actually clear the market here
        for i in range(matcher):
            if (self.b[i] > self.s[i]):
                self.count +=1
                self.last_price = self.b[i]
                
        return self.last_price
    
    # TODO: Annotate the ledger
    def annotate_ledger(self,clearing_price):
        ledger = self.book.get_ledger()
        for index, row in ledger.iterrows():
            if (row['role'] == 'seller'):
                if (row['price'] < clearing_price):
                    ledger.ix[index,'cleared'] = 'True'
                else:
                    ledger.ix[index,'cleared'] = 'False'
            else:
                if (row['price'] > clearing_price):
                    ledger.ix[index,'cleared'] = 'True'
                else:
                    ledger.ix[index,'cleared'] = 'False'  
                    
        self.book.update_ledger(ledger)
    
    def get_units_cleared(self):
        return self.count

Test DataFrame Appending


In [2]:
# Test the Book
ledger = pd.DataFrame(columns = ("role","name","price","cleared"))
ledger=ledger.append({"role":"seller","name":"gas","price":24,"cleared":"in process"},ignore_index=True)
ledger=ledger.append({"role":"buyer","name":"gas","price":25,"cleared":"in process"},ignore_index=True)
#df.append({'foo':1, 'bar':2}, ignore_index=True)
rows=ledger.loc[ledger['role'] == 'seller']
print(rows['price'].tolist())


[24.0]

In [3]:
for index, row in ledger.iterrows():
    if (row['role'] == 'seller'):
        print("yes","index")
        ledger.ix[index,'cleared']='True'
        row['cleared']='True'
    else:
        print("No change")
print()
print(ledger)


yes index
No change

     role name  price     cleared
0  seller  gas   24.0        True
1   buyer  gas   25.0  in process

Example Market

In the following code example we use the buyer and supplier objects to create a market. At the market a single price is announced which causes as many units of goods to be swapped as possible. The buyers and sellers stop trading when it is no longer in their own interest to continue.


In [4]:
# make a supplier and get the asks
supplier = Seller("Natural Gas")
supplier.set_quantity(100,0,10)

book = Book()
book.set_asks([supplier])

# make a buyer and get the bids
buyerNames = ('home', 'industry', 'cat')
buyerDictionary = {}
for name in buyerNames:
    buyerDictionary[name] = Buyer('%s' %name)

for obj in buyerDictionary.values():
    obj.set_quantity(100,0,10)

'''
# make a buyer and get the bids
buyer1 = Buyer("Home")
buyer1.set_quantity(100,0,10)

# make a buyer and get the bids
buyer2 = Buyer("Industry")
buyer2.set_quantity(100,0,10)
'''

book.set_bids([buy for buy in buyerDictionary.values()])
ledger = book.get_ledger()

gas_market = Market()
gas_market.add_seller(supplier)
gas_market.add_buyer(buyer1)
gas_market.add_buyer(buyer2)
gas_market.set_book()
asks = gas_market.get_asks()
#print(asks)

clearing = gas_market.get_clearing_price()
gas_market.annotate_ledger(clearing)
new_ledger = gas_market.get_ledger()

In [21]:
pd.DataFrame.head(new_ledger)


Out[21]:
role name price cleared
0 buyer Home 2.341344 False
1 buyer Home 6.621183 True
2 buyer Home 2.768160 False
3 buyer Home 8.059189 True
4 buyer Home 9.517614 True

Operations Research Formulation

The market can also be formulated as a very simple linear program or linear complementarity problem. It is clearer and easier to implement this market clearing mechanism with agents. One merit of the agent-based approach is that we don't need linear or linearizeable supply and demand function.

The auctioneer is effectively following a very simple linear program subject to constraints on units sold. The auctioneer is, in the primal model, maximizing the consumer utility received by customers, with respect to the price being paid, subject to a fixed supply curve. On the dual side the auctioneer is minimizing the cost of production for the supplier, with respect to quantity sold, subject to a fixed demand curve. It is the presumed neutrality of the auctioneer which justifies the honest statement of supply and demand.

An alternative formulation is a linear complementarity problem. Here the presence of an optimal space of trades ensures that there is a Pareto optimal front of possible trades. The perfect opposition of interests in dividing the consumer and producer surplus means that this is a zero sum game. Furthermore the solution to this zero-sum game maximizes societal welfare and is therefore the Hicks optimal solution.

Next Steps

A possible addition of this model would be to have a weekly varying demand of customers, for instance caused by the use of natural gas as a heating agent. This would require the bids and asks to be time varying, and for the market to be run over successive time periods. A second addition would be to create transport costs, or enable intermediate goods to be produced. This would need a more elaborate market operator. Another possible addition would be to add a profit maximizing broker. This may require adding belief, fictitious play, or message passing.

The object-orientation of the models will probably need to be further rationalized. Right now the market requires very particular ordering of calls to function correctly.


In [ ]:
# To 
# Create a dictionary for the properties of the agents

objectNames = ("foo", "bar", "cat", "mouse")
objectDictionary = {}
for name in objectNames:
    objectDictionary[name] = MyClass(property=foo,property2=bar)

for obj in objectDictionary.itervalues():
    obj.DoStuff(variable = foobar)